package com.zhixin.zhixinmall.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dtk.api.client.DtkApiClient;
import com.dtk.api.request.mastertool.DtkJdCommodityTransformLinkRequest;
import com.dtk.api.response.base.DtkApiResponse;
import com.dtk.api.response.mastertool.DtkJdCommodityTransformLinkResponse;
import com.zhixin.zhixinmall.entity.pojo.JdGoodPromotion;
import com.zhixin.zhixinmall.properties.DtkProperties;
import com.zhixin.zhixinmall.service.DtkService;
import com.zhixin.zhixinmall.service.JdGoodPromotionService;
import com.zhixin.zhixinmall.util.SnowflakeIdWorker;

/**
 * @author cyc
 * @date 2023/10/22 16:32:08
 */

@Service
public class DtkServiceImpl implements DtkService {

    @Autowired
    private DtkProperties dtkProperties;

    @Autowired
    private JdGoodPromotionService jdGoodPromotionService;

    private SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(0, 0);

    @Override
    public String promotionUnionConvert(Long skuId, String materialUrl) {
        JdGoodPromotion jdGoodPromotionBySkuid = jdGoodPromotionService.getJdGoodPromotionBySkuid(skuId);
        if (jdGoodPromotionBySkuid != null) {
            return jdGoodPromotionBySkuid.getPromotionUrl();
        }
        JdGoodPromotion jdGoodPromotion = new JdGoodPromotion();
        DtkApiResponse<DtkJdCommodityTransformLinkResponse> executeClient = executeClient(materialUrl);
        String url = executeClient.getData().getShortUrl();
        jdGoodPromotion.setId(snowflakeIdWorker.nextId());
        jdGoodPromotion.setMaterialUrl(materialUrl);
        jdGoodPromotion.setPromotionUrl(url);
        jdGoodPromotion.setSkuid(skuId);
        jdGoodPromotionService.insertJdGoodPromotion(jdGoodPromotion);
        return url;
    }

    private DtkApiResponse<DtkJdCommodityTransformLinkResponse> executeClient(String materialId) {
        DtkApiClient client = DtkApiClient.getInstance(dtkProperties.getAppKey(), dtkProperties.getAppSecret());
        DtkJdCommodityTransformLinkRequest request = new DtkJdCommodityTransformLinkRequest();
        request.setVersion("v1.0.0");
        request.setUnionId(dtkProperties.getUnionId());
        request.setChainType(2);
        request.setMaterialId(materialId);
        return client.execute(request);
    }

}
